﻿<template>
  <s-layout title="登录" :bgStyle="{ color: '#FFF' }">
    <view class="login-wrap">
      <view class="login-container">
        <view class="logo-section">
          <view class="brand-logo">
            <text class="logo-text">巴蜀客家</text>
            <view class="logo-decoration"></view>
          </view>
          <view class="welcome-text">欢迎回家</view>
          <view class="sub-text">传承客家文化，品味地道美食</view>
        </view>

        <view class="login-tabs">
          <!-- #ifdef MP-WEIXIN -->
          <view
            class="tab-item"
            :class="{ active: currentTab === 'wechat' }"
            @tap="switchTab('wechat')"
          >
            快捷登录
          </view>
          <!-- #endif -->
          <view
            class="tab-item"
            :class="{ active: currentTab === 'account' }"
            @tap="switchTab('account')"
          >
            账号登录
          </view>
        </view>

        <!-- #ifdef MP-WEIXIN -->
        <view v-if="currentTab === 'wechat'" class="login-form wechat-login">
          <view class="form-card wechat-card">
            <view class="wechat-login-desc">
              <view class="wechat-icon-large">🎋</view>
              <text class="desc-text">手机号快捷登录</text>
              <text class="desc-sub">安全便捷，一键登录巴蜀客家</text>
            </view>

            <button
              class="wechat-phone-btn"
              open-type="getPhoneNumber"
              @getphonenumber="wechatPhoneLogin"
              :loading="loading"
            >
              <view class="wechat-btn-content">
                <view class="wechat-btn-icon">
                  <text class="wechat-icon">📱</text>
                  <view class="icon-pulse"></view>
                </view>
                <text class="wechat-btn-text">手机号快捷登录</text>
              </view>
            </button>
          </view>
        </view>
        <!-- #endif -->

        <view v-if="currentTab === 'account'" class="login-form">
          <view class="form-card">
            <uni-forms
              ref="accountLoginRef"
              v-model="accountForm"
              :rules="accountRules"
              validateTrigger="bind"
            >
              <uni-forms-item name="mobile">
                <view class="input-container">
                  <view class="input-wrapper">
                    <view class="input-icon">
                      <view class="icon-bg">👤</view>
                    </view>
                    <uni-easyinput
                      placeholder="请输入账号/手机号"
                      v-model="accountForm.mobile"
                      :inputBorder="false"
                      :styles="inputStyles"
                    />
                  </view>
                  <view class="input-line"></view>
                </view>
              </uni-forms-item>

              <uni-forms-item name="password">
                <view class="input-container">
                  <view class="input-wrapper">
                    <view class="input-icon">
                      <view class="icon-bg">🔒</view>
                    </view>
                    <uni-easyinput
                      type="password"
                      placeholder="请输入密码"
                      v-model="accountForm.password"
                      :inputBorder="false"
                      :styles="inputStyles"
                    />
                  </view>
                  <view class="input-line"></view>
                </view>
              </uni-forms-item>
            </uni-forms>

            <view class="forgot-password">
              <text @tap="goToResetPassword">忘记密码？</text>
            </view>

            <button class="login-btn" @tap="accountLogin" :loading="loading">
              <view class="btn-content">
                <text class="btn-text">立即登录</text>
                <view class="btn-shine"></view>
              </view>
            </button>
          </view>
        </view>

        <view class="register-section">
          <text class="register-text">还没有账号？</text>
          <text class="register-link" @tap="goToRegister">立即注册</text>
        </view>

        <view class="agreement-section">
          <view class="agreement-checkbox" @tap="toggleAgreement">
            <view class="checkbox" :class="{ checked: agreedToTerms }">
              <text class="checkbox-icon">{{ agreedToTerms ? "✓" : "" }}</text>
            </view>
            <text class="agreement-text">
              我已阅读并同意
              <text class="link" @tap.stop="showProtocol('user')"
                >《用户协议》</text
              >
              和
              <text class="link" @tap.stop="showProtocol('privacy')"
                >《隐私政策》</text
              >
            </text>
          </view>
        </view>
      </view>
      <view class="decoration-elements">
        <view class="bamboo-left"></view>
        <view class="bamboo-right"></view>
        <view class="cloud-decoration cloud1"></view>
        <view class="cloud-decoration cloud2"></view>
      </view>
    </view>
  </s-layout>
</template>

<script setup>
import { reactive, ref, computed } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import sheep from "@/sheep";
import { mobile, password } from "@/sheep/validate/form";

const currentTab = ref("wechat");
const loading = ref(false);
const agreedToTerms = ref(false);

const accountLoginRef = ref(null);

const appInfo = computed(() => sheep.$store("app").info);

const accountForm = reactive({
  code: "",
  mobile: "",
  password: "",
  spreadUid: null,
});

const accountRules = {
  mobile,
  password,
};

const inputStyles = {
  borderBottom: "2px solid #DAA520",
  borderRadius: "0",
  paddingLeft: "0",
  paddingRight: "0",
  color: "#333",
};

function switchTab(tab) {
  currentTab.value = tab;
}

function toggleAgreement() {
  agreedToTerms.value = !agreedToTerms.value;
}

async function getWechatUserLoginCode() {
  try {
    await uni.login({
      provider: "weixin",
      success: (res) => {
        if (res.code) {
          accountForm.code = res.code;
        }
      },
    });
  } catch (error) {
    sheep.$helper.toast("获取登录信息失败");
  }
}

async function accountLogin() {
  if (!agreedToTerms.value) {
    sheep.$helper.toast("请先同意服务协议");
    return;
  }

  try {
    if (accountLoginRef.value) {
      await accountLoginRef.value.validate();
    }
  } catch (error) {
    return;
  }

  loading.value = true;
  try {
    const loginData = {
      ...accountForm,
      spreadUid: accountForm.spreadUid || null,
    };
    const result = await sheep.$api.user.accountLogin(loginData);

    if (result && result.token) {
      sheep.$helper.toast("登录成功！欢迎回到巴蜀客家！");
      await sheep.$store("user").getInfo();

      try {
        await sheep.$api.user.recordLogin();
      } catch (recordError) {
        // 忽略记录登录失败
      }

      // 登录成功后清除scene参数
      uni.removeStorageSync('sceneSpreadUid');

      const pages = getCurrentPages();
      if (pages.length > 1) {
        uni.navigateBack();
      } else {
        uni.switchTab({ url: "/pages/index/index" });
      }
    } else {
      sheep.$helper.toast("登录失败，请检查账号密码");
    }
  } catch (error) {
    sheep.$helper.toast(error || "登录失败，请重试");
  } finally {
    loading.value = false;
  }
}

// #ifdef MP-WEIXIN
async function wechatPhoneLogin(e) {
  if (!agreedToTerms.value) {
    sheep.$helper.toast("请先同意服务协议");
    return;
  }

  if (e.detail.errMsg !== "getPhoneNumber:ok") {
    sheep.$helper.toast("授权失败，请重试");
    return;
  }

  loading.value = true;
  try {
    await getWechatUserLoginCode();

    const phoneResult = await sheep.$api.user.getPhonenumber(e.detail.code);

    if (phoneResult) {
      accountForm.mobile = phoneResult;
      const wechatLoginData = {
        ...accountForm,
        spreadUid: accountForm.spreadUid || null,
      };
      const result = await sheep.$api.user.wechatLogin(wechatLoginData);

      if (result && result.token) {
        sheep.$helper.toast("登录成功！欢迎回到巴蜀客家！");
        await sheep.$store("user").getInfo();

        try {
          await sheep.$api.user.recordLogin();
        } catch (recordError) {
          // 忽略记录登录失败
        }

        // 登录成功后清除scene参数
        uni.removeStorageSync('sceneSpreadUid');

        const pages = getCurrentPages();
        if (pages.length > 1) {
          uni.navigateBack();
        } else {
          uni.switchTab({ url: "/pages/index/index" });
        }
      } else {
        sheep.$helper.toast("快捷登录失败，请重试");
      }
    }
  } catch (error) {
    sheep.$helper.toast("登录失败，请重试");
  } finally {
    loading.value = false;
  }
}
// #endif

function goToRegister() {
  uni.navigateTo({ url: "/pages/user/register" });
}

function goToResetPassword() {
  uni.navigateTo({ url: "/pages/user/reset-password" });
}

function showProtocol(type) {
  const protocolMap = {
    user: { id: "user_agreement", key: 'mall.userAgreement', title: "用户协议" },
    privacy: { id: "privacy_policy", key: 'mall.privacyAgreement', title: "隐私政策" },
  };

  const protocol = protocolMap[type];
  if (protocol) {
    sheep.$router.go("/pages/public/richtext", {
      id: protocol.id,
      title: protocol.title,
      key: protocol.key
    });
  }
}

onLoad((options) => {
  if (options.type) {
    currentTab.value = options.type;
  }

  if (options.spm) {
    const shareParams = sheep.$platform.share.decryptSpm(options.spm);
    if (shareParams && shareParams.shareId) {
      accountForm.spreadUid = shareParams.shareId;
    }
  } else if (options.spreadUid) {
    accountForm.spreadUid = options.spreadUid;
  }

  // 检查从首页扫码进入保存的scene参数
  const sceneSpreadUid = uni.getStorageSync('sceneSpreadUid');
  if (sceneSpreadUid && !accountForm.spreadUid) {
    accountForm.spreadUid = sceneSpreadUid;
  }
});
</script>

<style lang="scss" scoped>
$primary-color: #8b4513;
$secondary-color: #daa520;
$accent-color: #228b22;
$text-dark: #333;
$text-light: #666;
$bg-light: #fff8dc;

.login-wrap {
  position: relative;
  min-height: 100vh;
  background: linear-gradient(135deg, $primary-color 0%, #a0522d 100%);
  padding: 40rpx;
  overflow: hidden;
}

.login-container {
  position: relative;
  z-index: 2;
  background: white;
  border-radius: 30rpx;
  padding: 80rpx 50rpx 60rpx;
  box-shadow: 0 30rpx 60rpx rgba(0, 0, 0, 0.15);
  backdrop-filter: blur(10px);
  border: 2rpx solid rgba($secondary-color, 0.3);
}

.logo-section {
  text-align: center;
  margin-bottom: 60rpx;

  .brand-logo {
    margin-bottom: 30rpx;

    .logo-text {
      font-size: 56rpx;
      font-weight: bold;
      color: $primary-color;
      font-family: "楷体", "KaiTi", serif;
      text-shadow: 2rpx 2rpx 4rpx rgba(0, 0, 0, 0.1);
    }

    .logo-decoration {
      width: 120rpx;
      height: 6rpx;
      background: linear-gradient(
        90deg,
        transparent,
        $secondary-color,
        transparent
      );
      margin: 15rpx auto 0;
      border-radius: 3rpx;
    }
  }

  .welcome-text {
    font-size: 40rpx;
    font-weight: bold;
    color: $text-dark;
    margin-bottom: 15rpx;
    font-family: "楷体", "KaiTi", serif;
  }

  .sub-text {
    font-size: 26rpx;
    color: $text-light;
    letter-spacing: 2rpx;
  }
}

.login-tabs {
  display: flex;
  margin-bottom: 50rpx;
  background: rgba($bg-light, 0.5);
  border-radius: 15rpx;
  padding: 8rpx;
  border: 2rpx solid rgba($secondary-color, 0.2);

  .tab-item {
    flex: 1;
    text-align: center;
    padding: 20rpx 0;
    font-size: 28rpx;
    color: $text-light;
    position: relative;
    border-radius: 12rpx;
    transition: all 0.3s ease;
    font-family: "楷体", "KaiTi", serif;

    &.active {
      color: white;
      font-weight: bold;
      background: linear-gradient(135deg, $secondary-color 0%, #f4a460 100%);
      box-shadow: 0 8rpx 20rpx rgba($secondary-color, 0.3);
      transform: translateY(-2rpx);
    }
  }
}

.login-form {
  margin-bottom: 50rpx;

  .form-card {
    background: rgba(255, 255, 255, 0.95);
    border-radius: 25rpx;
    padding: 50rpx 40rpx;
    backdrop-filter: blur(10px);
    border: 2rpx solid rgba($secondary-color, 0.15);
    box-shadow:
      0 20rpx 40rpx rgba($primary-color, 0.1),
      inset 0 1rpx 0 rgba(255, 255, 255, 0.8);
    position: relative;
    overflow: hidden;

    &::before {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      height: 4rpx;
      background: linear-gradient(90deg, $primary-color, $secondary-color, $accent-color);
      border-radius: 25rpx 25rpx 0 0;
    }
  }

  :deep(.uni-forms-item) {
    margin-bottom: 50rpx;
  }

  .input-container {
    position: relative;
    margin-bottom: 10rpx;
  }

  .input-wrapper {
    display: flex;
    align-items: center;
    position: relative;
    background: rgba($bg-light, 0.5);
    border-radius: 15rpx;
    padding: 15rpx 20rpx;
    transition: all 0.3s ease;
    border: 2rpx solid transparent;

    &:hover {
      background: rgba($bg-light, 0.8);
      border-color: rgba($secondary-color, 0.3);
    }

    .input-icon {
      margin-right: 20rpx;

      .icon-bg {
        width: 50rpx;
        height: 50rpx;
        background: linear-gradient(135deg, $secondary-color, #F4A460);
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 24rpx;
        box-shadow: 0 6rpx 15rpx rgba($secondary-color, 0.3);

      }
    }

    :deep(.uni-easyinput) {
      flex: 1;
    }

    :deep(.uni-easyinput__content) {
      border: none !important;
      background: transparent !important;
      padding: 0 !important;
    }

    :deep(.uni-easyinput__content-input) {
      font-size: 32rpx !important;
      color: $text-dark !important;
      font-weight: 500 !important;
    }
  }

  .input-line {
    height: 3rpx;
    background: linear-gradient(90deg, transparent, $secondary-color, transparent);
    margin-top: 10rpx;
    border-radius: 2rpx;
    transform: scaleX(0);
    transition: transform 0.3s ease;
  }

  .input-container:focus-within .input-line {
    transform: scaleX(1);
  }

  .forgot-password {
    text-align: right;
    margin: 30rpx 0;

    text {
      font-size: 28rpx;
      color: $primary-color;
      font-weight: 500;
      position: relative;

      &::after {
        content: '';
        position: absolute;
        bottom: -3rpx;
        left: 0;
        width: 0;
        height: 2rpx;
        background: $primary-color;
        transition: width 0.3s ease;
      }

      &:active::after {
        width: 100%;
      }
    }
  }
}

.login-btn {
  width: 100%;
  height: 100rpx;
  background: linear-gradient(135deg, $primary-color 0%, #a0522d 100%);
  color: white;
  border: none;
  border-radius: 50rpx;
  font-size: 36rpx;
  font-weight: bold;
  box-shadow:
    0 15rpx 35rpx rgba($primary-color, 0.4),
    inset 0 2rpx 0 rgba(255, 255, 255, 0.2);
  position: relative;
  overflow: hidden;
  transition: all 0.3s ease;
  margin-top: 20rpx;

  &:active {
    transform: translateY(2rpx);
    box-shadow:
      0 10rpx 25rpx rgba($primary-color, 0.5),
      inset 0 2rpx 0 rgba(255, 255, 255, 0.2);
  }

  .btn-content {
    position: relative;
    z-index: 10;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
    width: 100%;
  }

  .btn-text {
    font-family: "楷体", "KaiTi", serif;
    letter-spacing: 3rpx;
    font-size: 36rpx;
    color: white;
    font-weight: bold;
    text-shadow: 1rpx 1rpx 2rpx rgba(0, 0, 0, 0.3);
    z-index: 11;
  }
}

.wechat-login {
  text-align: center;

  .wechat-card {
    background: linear-gradient(135deg, rgba(7, 193, 96, 0.1) 0%, rgba(5, 164, 80, 0.1) 100%);
    border: 2rpx solid rgba(7, 193, 96, 0.2);
  }

  .wechat-login-desc {
    margin-bottom: 50rpx;
    padding: 30rpx;
    text-align: center;

    .wechat-icon-large {
      font-size: 80rpx;
      margin-bottom: 20rpx;
      display: block;

    }

    .desc-text {
      display: block;
      color: $text-dark;
      font-size: 32rpx;
      font-weight: 600;
      margin-bottom: 10rpx;
      font-family: "楷体", "KaiTi", serif;
    }

    .desc-sub {
      display: block;
      color: $text-light;
      font-size: 26rpx;
      line-height: 1.5;
    }
  }

  .wechat-phone-btn {
    width: 100%;
    height: 100rpx;
    background: linear-gradient(135deg, #07c160 0%, #05a450 100%);
    color: white;
    border: none;
    border-radius: 50rpx;
    font-size: 32rpx;
    font-weight: bold;
    box-shadow:
      0 15rpx 35rpx rgba(7, 193, 96, 0.4),
      inset 0 2rpx 0 rgba(255, 255, 255, 0.2);
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;

    &:active {
      transform: translateY(2rpx);
      box-shadow:
        0 10rpx 25rpx rgba(7, 193, 96, 0.5),
        inset 0 2rpx 0 rgba(255, 255, 255, 0.2);
    }

          .wechat-btn-content {
        display: flex;
        align-items: center;
        justify-content: center;
        position: relative;
        z-index: 10;
        width: 100%;
        height: 100%;

        .wechat-btn-icon {
          margin-right: 20rpx;

          .wechat-icon {
            font-size: 40rpx;
            display: block;
          }
        }

        .wechat-btn-text {
          font-family: "楷体", "KaiTi", serif;
          letter-spacing: 2rpx;
          font-size: 34rpx;
          color: white;
          font-weight: bold;
          text-shadow: 1rpx 1rpx 2rpx rgba(0, 0, 0, 0.3);
        }
      }
  }
}

.register-section {
  text-align: center;
  margin: 50rpx 0;

  .register-text {
    font-size: 28rpx;
    color: $text-light;
  }

  .register-link {
    font-size: 28rpx;
    color: $primary-color;
    margin-left: 10rpx;
    font-weight: 500;
  }
}

.agreement-section {
  margin-top: 30rpx;

  .agreement-checkbox {
    display: flex;
    align-items: flex-start;
    font-size: 26rpx;
    color: $text-light;

    .checkbox {
      width: 36rpx;
      height: 36rpx;
      border: 3rpx solid #ddd;
      border-radius: 8rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 20rpx;
      flex-shrink: 0;
      margin-top: 2rpx;
      transition: all 0.3s ease;

      &.checked {
        background: $secondary-color;
        border-color: $secondary-color;
        box-shadow: 0 4rpx 12rpx rgba($secondary-color, 0.3);
      }

      .checkbox-icon {
        color: white;
        font-size: 24rpx;
        font-weight: bold;
      }
    }

    .agreement-text {
      flex: 1;
      line-height: 1.8;

      .link {
        color: $primary-color;
        font-weight: 500;
      }
    }
  }
}

// 装饰元素
.decoration-elements {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
  z-index: 1;

  .bamboo-left,
  .bamboo-right {
    position: absolute;
    width: 80rpx;
    height: 300rpx;
    background: linear-gradient(
      to bottom,
      rgba($accent-color, 0.1) 0%,
      rgba(darken($accent-color, 10%), 0.15) 50%,
      rgba($accent-color, 0.1) 100%
    );
    border-radius: 40rpx;
  }

  .bamboo-left {
    left: 20rpx;
    top: 150rpx;
    transform: rotate(-15deg);
  }

  .bamboo-right {
    right: 20rpx;
    top: 100rpx;
    transform: rotate(15deg);
  }

  .cloud-decoration {
    position: absolute;
    background: rgba(255, 255, 255, 0.1);
    border-radius: 50rpx;

    &.cloud1 {
      width: 150rpx;
      height: 60rpx;
      top: 10%;
      left: 8%;
      animation: float-left 8s ease-in-out infinite;
    }

    &.cloud2 {
      width: 120rpx;
      height: 50rpx;
      top: 75%;
      right: 10%;
      animation: float-right 6s ease-in-out infinite;
    }
  }
}

// 动画效果
@keyframes float-left {
  0%,
  100% {
    transform: translateX(0) translateY(0);
  }
  25% {
    transform: translateX(15rpx) translateY(-8rpx);
  }
  50% {
    transform: translateX(30rpx) translateY(0);
  }
  75% {
    transform: translateX(15rpx) translateY(8rpx);
  }
}

@keyframes float-right {
  0%,
  100% {
    transform: translateX(0) translateY(0);
  }
  25% {
    transform: translateX(-15rpx) translateY(8rpx);
  }
  50% {
    transform: translateX(-30rpx) translateY(0);
  }
  75% {
    transform: translateX(-15rpx) translateY(-8rpx);
  }
}

// 响应式调整
@media screen and (max-width: 750rpx) {
  .login-container {
    padding: 60rpx 40rpx 50rpx;
    margin: 20rpx;
  }

  .logo-section {
    margin-bottom: 50rpx;

    .brand-logo .logo-text {
      font-size: 48rpx;
    }

    .welcome-text {
      font-size: 36rpx;
    }
  }

  .login-tabs {
    margin-bottom: 40rpx;

    .tab-item {
      font-size: 26rpx;
      padding: 18rpx 0;
    }
  }
}
</style>
